import React, { Component, useMemo } from 'react'
import { View, Text } from '@tarojs/components'
import Taro, { getCurrentInstance } from '@tarojs/taro'
import { timestampToTime, transformData } from '@/utils'
import { SpNavBar } from '@/components'
import api from '@/api'
import './editLocation.scss'
import UploadUtil from '@/utils/UploadUtil'
import { connect } from 'react-redux'
import {
    Form,
    Input,
    Button,
    Cascader,
    TextArea,
    Space,
    Dialog
} from 'antd-mobile'
import cart from '@/store/slices/cart'
class EditLocation extends Component {
    formRef = React.createRef()
    constructor(props) {
        super(props);
        this.state = {
            items: [],
            regions: [],
            regions_id: [],
            lat: '',
            lng: '',
            placeSearch: '',
        }
    }
    componentDidMount() {
        this.getAdressItem()
        const {
            router: {
                params: { id }
            }
        } = getCurrentInstance()
        this.getShopDetail(id)

    }
    async getAdressItem() {
        const data = await api.address.areaList()
         this.setState({
            items: data
        })

    }
    searchLoction = () => {
        // //关键字查询
        const values = this.formRef.current?.getFieldsValue()
        console.log('000000', values)
        if (values.regions_id.length == 0) {
            this.$message.error('请选择地区')
            return
        }
        if (!values.address) {
            this.$message.error('请输入具体位置')
            return
        }
        this.state.placeSearch.setCity(this.state.regions[2])
        this.state.placeSearch.search(values.address, function (status, result) {

        });
    }
    async getShopDetail(id) {
        const form = await api.shop.getMerchantById({ 'distributor_id': id })
     this.setState({
            // form: form,
            regions_id: form.regions_id,
            regions: form.regions,
            lat: form.lat,
            lng: form.lng
        })
        await this.formRef.current?.setFieldsValue(form)
        this.initAmap()
    }
    initAmap() {

        var map = new AMap.Map("location-container", {
            zoom: 13,//级别
            center: [this.state.lng, this.state.lat],//中心点坐标
            resizeEnable: true
        });
        var that = this
        AMap.service(["AMap.PlaceSearch"], async function () {
            //构造地点查询类
            var placeSearch = new AMap.PlaceSearch({
                pageSize: 5, // 单页显示结果条数
                pageIndex: 1, // 页码
                city: "", // 兴趣点城市
                citylimit: true,  //是否强制限制在设置的城市内搜索
                map: map, // 展现结果的地图实例
                autoFitView: true // 是否自动调整地图视野使绘制的 Marker点都处于视口的
            });
            await that.setState({ placeSearch: placeSearch })
            const marker = new AMap.Marker({
                position: new AMap.LngLat(that.state.lng, that.state.lat),   // 经纬度对象，也可以是经纬度构成的一维数组[116.39, 39.9]
            });
            map.add(marker);

            // // 为marker注册点击事件
            placeSearch.on('markerClick', function (e) {
                console.log('==========', e)
                that.setState({
                    lng: e.data.location.lng,
                    lat: e.data.location.lat
                })
            });
        });
    }
    getRegionNameById(region, district) {
        let result = []
        function getRegionName(_district, index) {
            const res = _district.find((item) => item.value == region[index])
            if (res) {
                result.push(res.label)
                if (res.children) {
                    getRegionName(res.children, ++index)
                }
            }
        }
        if (Array.isArray(region) && region.length > 0) {
            getRegionName(district, 0)
        }
        return result
    }
    onFinish = (values) => {
        console.log(values)
        if (values.quantity) {

        }
        this.onSubmit(values)
    }
    onSubmit = async () => {

        const values = this.formRef.current?.getFieldsValue()
        // Dialog.alert({
        //     content: <pre>{JSON.stringify(values, null, 2)}</pre>,
        // })

        var params = {
            ...JSON.parse(JSON.stringify(values)),
            lat:this.state.lat,
            lng:this.state.lng
        }
        console.log(params)
        const {
            router: {
                params: { id }
            }
        } = getCurrentInstance()

        params.distributor_id = id
        await api.shop.editMerchant(params)

        Taro.navigateBack()
    }
    state = {}
    render() {
        return (
            <View >
                <SpNavBar title='店铺位置'></SpNavBar>
                <View className='edit-location'>
                    <Form ref={this.formRef}
                        layout='horizontal'
                        footer={
                            <Button block type='submit' color='primary' size='large' >
                                提交
                            </Button>
                        }
                        onFinish={this.onFinish}
                        onFinishFailed={this.onFinishFailed}
                        initialValues={{}}>
                        <Form.Item label="地理位置" name='regions_id'
                            trigger='onConfirm'
                            rules={[{ required: true, message: '请选择地址' }]}
                            onClick={(e, datePickerRef) => {
                                datePickerRef.current?.open() // ⬅️
                            }}
                        >
                            <Cascader
                                options={this.state.items}
                                value={this.state.regions_id}
                                onChange
                            >
                                {items => {
                                    if (items.every(item => item === null)) {
                                        return '未选择'
                                    } else {
                                        this.state.regions = items.map(item => item?.label ?? '未选择')
                                        return items.map(item => item?.label ?? '未选择').join('-')
                                    }
                                }}
                            </Cascader>
                        </Form.Item>
                        <Form.Item name='address' label='详细地址'
                            rules={[{ required: true, message: '详细地址不能为空' }]}>
                            <TextArea
                                placeholder='请填写详细地址'
                                maxLength={100}
                                showCount
                            />
                        </Form.Item>
                        <Form.Item>
                            <Button block color='primary' size='large' onClick={this.searchLoction}>
                                搜索
                            </Button>
                        </Form.Item>
                        <Form.Item name='lat' label='店铺经纬度'>
                            <Space>
                                <Text>{this.state.lat}</Text>
                                <Text>——</Text>
                                <Text>{this.state.lng}</Text>
                            </Space>
                        </Form.Item>
                        <Form.Item>
                            <View id="location-container"></View>
                        </Form.Item>

                    </Form>

                </View>


            </View >
        );
    }
}

export default EditLocation;